<?php

namespace App\Store\Controllers\Financial\Business;

use App\Common\Services\CommonExcelExport;
use App\Common\Services\Store\Common as StoreCommon;
use App\Http\Controllers\Controller;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\OldMaterial\AllotInfolist;
use App\Store\Models\OldMaterial\ReturnFactoryInfolist;
use App\Store\Models\OldMaterial\Stock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class OldMaterialController extends Controller
{
    public function getlist(Request $request)
    {
        $data = $this->getdata($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $data]);
    }

    public function doexport(Request $request)
    {
        $data = $this->getdata($request);

        if (!$data) {
            return response()->json(['code' => '001', 'msg' => '导出失败']);
        }
        $storeNames = array_unique(array_map(function ($item) {
            return $item['store_name'];
        }, $data));
        $row = [
            ['store_name' => '旧料统计表'],
            ['store_name' => '所属门店：' . join(',', $storeNames)],
            [
                'store_name' => '所属门店',
                'goods_category_id' => '类别',
                'stock_in_weight' => '回收入库-重量',
                'stock_in_count' => '回收入库-件数',
                'stock_in_exchange_amount' => '回收入库-换货金额',
                'cut_out_weight' => '截金入库-重量',
                'cut_out_exchange_amount' => '截金入库-金额',
                'return_weight' => '返厂出库-重量',
                'return_count' => '返厂出库-件数',
                'return_exchange_amount' => '返厂出库-换货金额',
                'allot_out_weight' => '调拨出库-重量',
                'allot_out_count' => '调拨出库-件数',
                'allot_out_exchange_amount' => '调拨出库-换货金额',
                'allot_out_dold_fee' => '调拨出库-折旧工费',
                'allot_in_weight' => '调拨入库-重量',
                'allot_in_count' => '调拨入库-件数',
                'allot_in_exchange_amount' => '调拨入库-换货金额',
                'allot_in_dold_fee' => '调拨入库-折旧工费',
                'total_weight' => '合计-重量',
                'total_count' => '合计-件数',
                'total_exchange_amount' => '合计-换货金额',
                'total_dold_fee' => '合计-折旧工费',
            ]];

        $exceldata = [];
        foreach ($data as $val) {
            $exceldata[] = [
                'store_name' => $val['store_name'],
                'goods_category_id' => $val['goods_category_name'],
                'stock_in_weight' => isset($val['stock_in']['weight']) ? $val['stock_in']['weight'] : '0',
                'stock_in_count' => isset($val['stock_in']['count']) ? $val['stock_in']['count'] : '0',
                'stock_in_exchange_amount' => isset($val['stock_in']['exchange_amount']) ? $val['stock_in']['exchange_amount'] / 100 : '0',
                'cut_out_weight' => isset($val['cut_out']['weight']) ? $val['cut_out']['weight'] : '0',
                'cut_out_exchange_amount' => isset($val['cut_out']['exchange_amount']) ? $val['cut_out']['exchange_amount'] / 100 : '0',
                'return_weight' => isset($val['return']['weight']) ? $val['return']['weight'] : '0',
                'return_count' => isset($val['return']['count']) ? $val['return']['count'] : '0',
                'return_exchange_amount' => isset($val['return']['exchange_amount']) ? $val['return']['exchange_amount'] / 100 : '0',
                'allot_out_weight' => isset($val['allot_out']['weight']) ? $val['allot_out']['weight'] : '0',
                'allot_out_count' => isset($val['allot_out']['count']) ? $val['allot_out']['count'] : '0',
                'allot_out_exchange_amount' => isset($val['allot_out']['exchange_amount']) ? $val['allot_out']['exchange_amount'] / 100 : '0',
                'allot_out_dold_fee' => isset($val['allot_out']['dold_fee']) ? $val['allot_out']['dold_fee'] / 100 : '0',
                'allot_in_weight' => isset($val['allot_in']['weight']) ? $val['allot_in']['weight'] : '0',
                'allot_in_count' => isset($val['allot_in']['count']) ? $val['allot_in']['count'] : '0',
                'allot_in_exchange_amount' => isset($val['allot_in']['exchange_amount']) ? $val['allot_in']['exchange_amount'] / 100 : '0',
                'allot_in_dold_fee' => isset($val['allot_in']['dold_fee']) ? $val['allot_in']['dold_fee'] / 100 : '0',
                'total_weight' => isset($val['total']['weight']) ? $val['total']['weight'] : '0',
                'total_count' => isset($val['total']['count']) ? $val['total']['count'] : '0',
                'total_exchange_amount' => isset($val['total']['exchange_amount']) ? $val['total']['exchange_amount'] / 100 : '0',
                'total_dold_fee' => isset($val['total']['dold_fee']) ? $val['total']['dold_fee'] / 100 : '0',
            ];
        }

        $filename = '旧料报表导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    public function getdata(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);


        if(!empty($request['store_id'])){
            $store_ids=is_array($request['store_id'])?$request['store_id']:[$request['store_id']];
        }else{
            $store_ids = StoreCommon::getCurrentAccountStoreId($request);
            $store_ids = is_array($store_ids) ? $store_ids : ($store_ids>0?[$store_ids]:[]);
        }


        $where['is_del']=1;
        $where['cp_id']=$accountinfo['cp_id'];


        if (!empty($request['goods_brand_id'])) {
            $where['goods_brand_id']=$request['goods_brand_id'];
        }

        if (!empty($request['goods_style_id'])) {
            $where['goods_brand_id']=$request['goods_brand_id'];

        }

        if (!empty($request['goods_category_id'])) {
            $where['goods_category_id']=$request['goods_category_id'];

        }

        $start_time = (!is_numeric($request->start_time) && strtotime($request->start_time) > 0) ? strtotime($request->start_time) : intval($request->start_time);
        $end_time = (!is_numeric($request->end_time) && strtotime($request->end_time) > 0) ? strtotime($request->end_time) : intval($request->end_time);
        if ($start_time > 0 && $end_time > $start_time) {
            $where[] = ['create_at', '>=', $start_time];
            $where[] = ['create_at', '<=', $end_time];
        }

        //入库
        $query = Stock::with(['storeinfo', 'goods_category'])->where($where);
        if (!empty($store_ids)) {
            $query = $query->whereIn('store_id', $store_ids);
        }

        $list = $query->groupBy('goods_category_id')->select('store_id', 'goods_category_id', DB::raw('sum(piece_weight_new) as weight, sum(count) as count, sum(exchange_amount) as exchange_amount'))->get()->toArray();
        $stock = [];
        foreach ($list as $v) {
            $stock[$v['goods_category_id']]['store_name'] = $v['storeinfo']['store_name'] ?? '';
            $stock[$v['goods_category_id']]['goods_category_name'] = $v['goods_category']['category_name'] ?? '';
            $stock[$v['goods_category_id']]['stock_in'] = $v;
        }


        //返厂出库
        $query = ReturnFactoryInfolist::with(['storeinfo', 'goods_category'])->where($where);
        if (!empty($store_ids)) {
            $query = $query->whereIn('store_id', $store_ids);
        }

        $return = [];
        $list = $query->groupBy('goods_category_id')->select('store_id', 'goods_category_id', DB::raw('sum(piece_weight_new) as weight, sum(audit_success_count) as count, sum(exchange_amount) as exchange_amount'))->get()->toArray();
        foreach ($list as $v) {
            $return[$v['goods_category_id']]['store_name'] = $v['storeinfo']['store_name'] ?? '';
            $return[$v['goods_category_id']]['goods_category_name'] = $v['goods_category']['category_name'] ?? '';
            $return[$v['goods_category_id']]['return'] = $v;
        }

        //调拨入库
        $whereAllot =$where;
        $whereAllot['audit_status']=2;
        unset($whereAllot['store_id']);


        $query = AllotInfolist::with(['storeinfo', 'target_goods_category'])->where($whereAllot);
        if (!empty($store_ids)) {
            $query = $query->whereIn('target_store_id', $store_ids);
        }
        $allot_in = [];
        $list = $query->groupBy('target_category_id')
            ->select('start_store_id', 'target_category_id as goods_category_id', DB::raw('sum(piece_weight_new) as weight, sum(audit_success_count) as count, sum(exchange_amount) as exchange_amount, sum(dold_fee) as dold_fee'))->get()->toArray();
        foreach ($list as $v) {
            $allot_in[$v['goods_category_id']]['store_name'] = $v['storeinfo']['store_name'] ?? '';
            $allot_in[$v['goods_category_id']]['goods_category_name'] = $v['goods_category']['category_name'] ?? '';
            $allot_in[$v['goods_category_id']]['allot_in'] = $v;
        }

        //调拨出库
        $query = AllotInfolist::with(['storeinfo', 'goods_category'])->where($where)->where('audit_status',2);;
        if (!empty($store_ids)) {
            $query = $query->whereIn('store_id', $store_ids);
            $query = $query->whereIn('start_store_id', $store_ids);
        }

        $list = $query->groupBy('goods_category_id')->select('start_store_id', 'goods_category_id', DB::raw('sum(piece_weight_new) as weight, sum(audit_success_count) as count, sum(exchange_amount) as exchange_amount, sum(dold_fee) as dold_fee'))->get()->toArray();
        $allot_out = [];
        foreach ($list as $v) {
            $allot_out[$v['goods_category_id']]['store_name'] = $v['storeinfo']['store_name'] ?? '';
            $allot_out[$v['goods_category_id']]['goods_category_name'] = $v['goods_category']['category_name'] ?? '';
            $allot_out[$v['goods_category_id']]['allot_out'] = $v;
        }

        //库存
        $query = Stock::with(['storeinfo', 'goods_category'])->where($where);
        if (!empty($store_ids)) {
            $query = $query->whereIn('store_id', $store_ids);
        }
        $total = [];
        $list = $query->groupBy('goods_category_id')->select('store_id', 'goods_category_id', DB::raw('sum(piece_weight_new) as weight, sum(count) as count, sum(exchange_amount) as exchange_amount, sum(dold_fee) as dold_fee'))->get()->toArray();
        foreach ($list as $v) {
            $total[$v['goods_category_id']]['store_name'] = $v['storeinfo']['store_name'] ?? '';
            $total[$v['goods_category_id']]['goods_category_name'] = $v['goods_category']['category_name'] ?? '';
            $total[$v['goods_category_id']]['total'] = $v;
        }

        //截金
        $query = Stock::with(['storeinfo', 'goods_category'])->where($where)->where(['stock_type' => 3]);
        if (!empty($store_ids)) {
            $query = $query->whereIn('store_id', $store_ids);
        }
        $cut_out = [];
        $list = $query->groupBy('goods_category_id')->select('store_id', 'goods_category_id', DB::raw('sum(netglod_weight) as weight, sum(exchange_amount) as exchange_amount'))->get()->toArray();
        foreach ($list as $v) {
            $cut_out[$v['goods_category_id']]['store_name'] = $v['storeinfo']['store_name'] ?? '';
            $cut_out[$v['goods_category_id']]['goods_category_name'] = $v['goods_category']['category_name'] ?? '';
            $cut_out[$v['goods_category_id']]['cut_out'] = $v;
        }

        // 补全分类下，没有数据的情况
        $cateList = GoodsCategory::query()
            ->join('site_store_list', 'site_basic_goods_category.store_id', '=', 'site_store_list.id')
            ->where('site_basic_goods_category.is_del', 1)
            ->where('site_basic_goods_category.cp_id', $accountinfo['cp_id'])
            ->when(!empty($store_ids), function ($query) use ($store_ids) {
                $query->whereIn('store_id', $store_ids);
            })
            ->selectRaw('zxb_site_basic_goods_category.*,zxb_site_store_list.store_name as store_name')
            ->get()
            ->toArray();

        $data = [];

        foreach ($cateList as $item) {
            $arr_stock_in = $stock[$item['id']]['stock_in'] ?? [];
            $arr_return = $return[$item['id']]['return'] ?? [];
            $arr_allot_in = $allot_in[$item['id']]['allot_in'] ?? [];
            $arr_allot_out = $allot_out[$item['id']]['allot_out'] ?? [];
            $arr_total = $total[$item['id']]['total'] ?? [];
            $arr_cut_out = $cut_out[$item['id']]['cut_out'] ?? [];
            if (!empty($arr_stock_in) ||!empty($arr_return)||!empty($arr_allot_in)||!empty($arr_allot_out)||!empty($arr_total)||!empty($arr_cut_out)){
                $data[$item['id']]['goods_category_id'] = $item['id'];
                $data[$item['id']]['store_name'] = $item['store_name'];
                $data[$item['id']]['goods_category_name'] = $item['category_name'];
                $data[$item['id']]['stock_in'] = $arr_stock_in;
                $data[$item['id']]['return'] = $arr_return;
                $data[$item['id']]['allot_in'] = $arr_allot_in;
                $data[$item['id']]['allot_out'] = $arr_allot_out;
                $data[$item['id']]['total'] = $arr_total;
                $data[$item['id']]['cut_out'] = $arr_cut_out;
            }
        }
        return array_values($data);
    }
}
